package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.Login;
import com.isunland.managesystem.entity.RetrievePasswordParams;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.json.JSONException;

/**
 * Created by wu on 2016/5/24.
 * 韦加登陆
 */
public class LoginFragment extends Fragment {
    protected static final String TAG = LoginFragment.class.getSimpleName();
    /**
     * 找回密码
     */
    private static final int REQUEST_RETRIEVE_PASSWORD = 1;
    private static final int REQUEST_REGISTER = 2;
    private EditText mETUserName;
    private EditText mETPassword;
    private CheckBox mCBRemeberMe;
    private String mUsername;
    private String mPassword;
    private SingleFragmentActivity mActivity;
    private CurrentUser mUser;
    private ProgressDialog progressDialog;
    private View mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mUser = CurrentUser.newInstance(getActivity());
        mUsername = mUser.getName();
        mPassword = mUser.getPassword();
        mActivity = (SingleFragmentActivity) getActivity();
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.activity_first_newlogin_wj, container, false);
        findViews(mView);
        return mView;
    }

    private void findViews(View v) {
        mETUserName = (EditText) v.findViewById(R.id.username);

        //        mETPassword = (PasswordTextInput) v.findViewById(R.id.password);
        mETPassword = (EditText) v.findViewById(R.id.password);
        mCBRemeberMe = (CheckBox) v.findViewById(R.id.rememberMe);
        TextView tvAppName = (TextView) v.findViewById(R.id.tv_appName);
        //国欣ERP+改为角标
        tvAppName.setText(MyUtils.getAppNameHtml(mActivity));
        mETUserName.setText(mUsername);
        mETPassword.setText(mPassword);
        mETPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    doLogin();
                    return true;
                }
                return false;
            }
        });
        showDiffRegister(v);
        // 点击配置服务器路径,正式版需隐藏
        ifShowDevOption(v);
        //人名任命选择，方便开发时切换账号。正式版本禁用。
        ifSelectNames(v);
        View loginBtn = v.findViewById(R.id.login);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //登录
                doLogin();
            }
        });

        //离线打卡
        TextView outLine = (TextView) v.findViewById(R.id.tv_outlineSign_settingFragment);
        outLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AttendanceOutlineActivity.class);
                startActivity(intent);
            }
        });
        //找回密码
        TextView tvRetrievePassword =
                (TextView) v.findViewById(R.id.tv_retrievePassword_settingFragment);
        tvRetrievePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RetrievePasswordParams params = new RetrievePasswordParams();
                params.setAccout(MyStringUtil.getText(mETUserName));
                BaseVolleyActivity.newInstance(LoginFragment.this, RetrievePasswordActivity.class, params,
                        REQUEST_RETRIEVE_PASSWORD);
            }
        });

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage(getString(R.string.loadingLogin));
        progressDialog.setCancelable(true);
    }

    /**
     * 点击配置服务器路径,正式版需隐藏
     */
    private void ifShowDevOption(View v) {
        TextView tvDevOption = (TextView) v.findViewById(R.id.tv_devOption);

        if (MyUtils.isDevelopMode(mActivity)) {
            tvDevOption.setVisibility(View.VISIBLE);
            tvDevOption.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    startActivity(new Intent(mActivity, TestActivity.class));
                    //FragmentManager fm = getActivity().getSupportFragmentManager();
                    //NetWorkSettingDialogFragment dialog = new NetWorkSettingDialogFragment();
                    //dialog.show(fm, "dialogSettingNetwork");
                }
            });
        } else {
            tvDevOption.setVisibility(View.GONE);
        }
    }

    private void showDiffRegister(View v) {
        TextView mtv_resetting_settingFragment =
                (TextView) v.findViewById(R.id.tv_resetting_settingFragment);
        mtv_resetting_settingFragment.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                BaseVolleyActivity.newInstance(LoginFragment.this,
                        MyUtils.isWeiJia() ? RegisterPagerActivity.class : RegisterDetailActivity.class, null,
                        REQUEST_REGISTER);
            }
        });
    }

    private void doLogin() {

        mUsername = mETUserName.getText().toString().trim();
        mPassword = mETPassword.getText().toString().trim();
        if (TextUtils.isEmpty(mUsername)) {
            Toast.makeText(getActivity(), R.string.emptyName, Toast.LENGTH_SHORT).show();
            mETUserName.setFocusable(true);
            return;
        }
        if (mUsername.equalsIgnoreCase("#.dev")) {
            MyUtils.setDevelopMode(mActivity, !MyUtils.isDevelopMode(mActivity));
            ifSelectNames(mView);
            ifShowDevOption(mView);
        }
        if (TextUtils.isEmpty(mPassword)) {
            Toast.makeText(getActivity(), R.string.emptyPassword, Toast.LENGTH_SHORT).show();
            mETPassword.setFocusable(true);
            return;
        }

        volleyPostLogin();
    }

    //    void update() {
    //        Intent intent = new Intent(Intent.ACTION_VIEW);
    //        intent.setDataAndType(
    //                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/bpmx33_android.apk")),
    //                "application/vnd.android.package-archive");
    //        startActivity(intent);
    //    }

    private void volleyPostLogin() {

        RequestManager.ClearCookie();
        String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LOGIN);
        HashMap<String, String> params = new HashMap<>();

        params.put("username", mUsername);
        params.put("password", mPassword);
        if (!MyUtils.isNetLink(getActivity())) {
            ToastUtil.show(R.string.network_error);

            return;
        }
        progressDialog.show();
        mActivity.volleyPost(url, params, new VolleyResponse() {

            @Override
            public void onVolleyResponse(String arg0) throws JSONException {
                if (!progressDialog.isShowing()) {
                    // no longer attached to activity!
                    return;
                }
                progressDialog.dismiss();
                SharedPreferencesUtil.setString(getActivity(), SharedPreferencesUtil.COOKIE,
                        RequestManager.getCookie());
                LogUtil.i(TAG, "cookie=" + RequestManager.getCookie());
                handleResponse(arg0);
            }

            @Override
            public void onVolleyError(VolleyError arg0) {
                if (!progressDialog.isShowing()) {
                    // no longer attached to activity!
                    return;
                }
                progressDialog.dismiss();
            }
        });
    }

    private void handleResponse(String response) {
        LogUtil.i(TAG, "response=" + response);
        MyUtils.dismissDialog();
        try {
            Login login = new Gson().fromJson(response, Login.class);
            if (login == null) return;
            if ((login.isSuccess() == null) || (!login.isSuccess())) {
                Toast.makeText(getActivity(), login.getMsg(), Toast.LENGTH_SHORT).show();
                return;
            }

            Toast.makeText(getActivity(), R.string.login_success, Toast.LENGTH_SHORT).show();

            if (mCBRemeberMe.isChecked()) {
                mUser.update(mUsername, mPassword, login.getUserName(), login.getUserId() + "",
                        login.getMemberCode(), login.getJobNo(), login.getPicture(),
                        login.getPhoneIdentifyNumber(), login.getDeptCode(), login.getPushClientId(),
                        login.getDeptName(), login.getKeypositionName(), login.getEmail(),
                        login.getMemberName(), login.getMobile(), login.getManageOrgCode(),
                        login.getManageOrgName(), true);
            } else {

                mUser.update("", "", login.getUserName(), login.getUserId() + "", login.getMemberCode(),
                        login.getJobNo(), login.getPicture(), login.getPhoneIdentifyNumber(),
                        login.getDeptCode(), login.getPushClientId(), login.getDeptName(),
                        login.getKeypositionName(), login.getEmail(), login.getMemberName(), login.getMobile(),
                        login.getManageOrgCode(), login.getManageOrgName(), true);
            }

            if (MyUtils.isDevelopMode(mActivity)) {
                MyUtils.addPath(ApiConst.sUrlMain);
                MyUtils.addUser(mUsername, mPassword);
            }

            Intent i = new Intent(getActivity(), GuideMenuNewActivity.class);
            startActivity(i);
        } catch (Exception e) {
            LogUtil.e(TAG, "errorMsg", e);
            Toast.makeText(getActivity(), R.string.login_failure, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 人名任命选择，方便开发时切换账号。正式版本禁用。
     */
    private void ifSelectNames(View v) {
        ImageView mNameIv = (ImageView) v.findViewById(R.id.iv_name);
        if (MyUtils.isDevelopMode(mActivity)) {
            mNameIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showDialogNames(MyUtils.getUserNames());
                }
            });
        } else {
            mNameIv.setOnClickListener(null);
        }
    }

    private void showDialogNames(final LinkedHashMap<String, String> map) {
        if (map == null || map.size() == 0) return;
        ArrayList<String> nameArr = new ArrayList<>(map.keySet());
        Collections.sort(nameArr, new Comparator<String>() {
            public int compare(String mapping1, String mapping2) {
                return mapping1.compareTo(mapping2);
            }
        });
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(mActivity);
        //builderSingle.setIcon(R.drawable.ic_launcher);
        builderSingle.setTitle("Select One Name:");

        final ArrayAdapter<String> arrayAdapter =
                new ArrayAdapter<>(mActivity, android.R.layout.select_dialog_singlechoice);
        arrayAdapter.addAll(nameArr);
        builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                //LogUtil.i("mEtUsername=" + strName + ",pwd=" + mNameMap.get(strName));
                mETUserName.setText(strName);
                mETPassword.setText(map.get(strName));
            }
        });
        builderSingle.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (requestCode == REQUEST_REGISTER && data != null) {
            String userName = data.getStringExtra(RegisterFragment.EXTRA_USERNAME);
            String password = data.getStringExtra(RegisterFragment.EXTRA_PASSWORD);
            mETUserName.setText(userName);
            mETPassword.setText(password);
        }
        if (requestCode == REQUEST_RETRIEVE_PASSWORD && data != null) {
            String userName = data.getStringExtra(RetrievePasswordFragment.EXTRA_USERNAME);
            String password = data.getStringExtra(RetrievePasswordFragment.EXTRA_PASSWORD);
            mETUserName.setText(userName);
            mETPassword.setText(password);
        }
    }
}
